package com.base.caselib.presenter;

import android.app.Activity;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.arvin.imagepicker.bean.ImageItem;
import com.base.caselib.bean.CarInfo;
import com.base.caselib.bean.PeopleInfoBean;
import com.base.caselib.bean.RegPeopleBean;
import com.base.caselib.view.RegistPersonView;
import com.base.commonlib.base.BaseApp;
import com.base.commonlib.base.presenter.BasePresenter;
import com.base.commonlib.http.CallBackFroPark;
import com.base.commonlib.http.FileBean;
import com.base.commonlib.http.RealNetWorkUtil;
import com.base.commonlib.http.ResponseT;
import com.base.commonlib.http.utils.CallBackImpl;
import com.base.commonlib.utils.BitmapUtil;
import com.base.commonlib.utils.ToastUtil;
import com.base.commonlib.widget.CommonDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;

/**
 * Created by weikailiang on 2020/2/5.
 */

public class RegistPersonPresenter extends BasePresenter<RegistPersonView> implements AMapLocationListener {
    /**
     * 声明mlocationClient对象
     */
    private AMapLocationClient mLocationClient;
    /**
     * 声明mLocationOption对象
     */
    public AMapLocationClientOption mLocationOption = null;
    public RegistPersonPresenter(RegistPersonView view, Activity activity) {
        super(view, activity);
    }
    public void startLocationForLl(){
        mLocationClient = new AMapLocationClient(mActivity);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);
        mLocationOption.setHttpTimeOut(8000);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setLocationCacheEnable(true);
        // 设置定位监听
        mLocationClient.setLocationListener(this);
        // 设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        startMapLocation();
    }
    /**
     * 开启定位
     */
    public void startMapLocation() {
        //判断是否开启了，没有开启就开启
        if (!mLocationClient.isStarted()) {
            mLocationClient.startLocation();
        }
    }

    /**
     * 停止定位服务
     */
    public void stopMapLocation() {
        //判断服务是否开启了，若开启了则停止
        if (mLocationClient.isStarted()) {
            mLocationClient.stopLocation();
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                // 可在其中解析amapLocation获取相应内容。
                //给接口设置数据
                if (TextUtils.isEmpty(aMapLocation.getAddress())||aMapLocation.getAddress() == null){
                    return;
                }
                mView.returnLocation(aMapLocation);
                stopMapLocation();
            } else {
                mView.showMes("定位权限未开启");
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                stopMapLocation();
            }
        } else {
            stopMapLocation();
        }
    }


    @Override
    public void release() {
        super.release();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
    }



    public void up(final PeopleInfoBean info){
        mView.showPb_mes("正在压缩图片。。。");
        List<String> paths = new ArrayList<>();
        if (info.getPhoteFiles()!=null) {
            for (String fils : info.getPhoteFiles()) {
                paths.add(BitmapUtil.compressImage(fils));
            }
        }

        List<String> paths1 = new ArrayList<>();
        if (info.getSfzFiles()!=null) {
            for (String fils : info.getSfzFiles()) {
                paths1.add(BitmapUtil.compressImage(fils));
            }
        }

        //压缩完成
        mView.hidePb_mes();

        mView.showPb_mes("正在保存数据");
        final List<FileBean> mFileList = new ArrayList<>();
        FileBean mFileBean = null;
        for (String str : paths){
            mFileBean = new FileBean("photeFiles",str);
            mFileList.add(mFileBean);
        }
        for (String str : paths1){
            mFileBean = new FileBean("sfzFiles",str);
            mFileList.add(mFileBean);
        }


        Disposable enqueue = RealNetWorkUtil.postPics().method("api-sms/communityPeople/save").filePaths(mFileList)
                .addParams("phone",info.getPhone())
                .addParams("address",info.getAddress())
                .addParams("checkPoint",info.getCheckPoint())
                .addParams("areaContact",info.getAreaContact())
                .addParams("febrileState",info.getFebrileState())
                .addParams("isLocalHousehold",info.getIsLocalHousehold())
                .addParams("outWay",info.getOutWay())
                .build().enqueueForUpFiles(new CallBackFroPark<ResponseT>() {
                    @Override
                    public void onResponse(ResponseT responseT) throws Exception {
                        mView.hidePb_mes();
                        mView.showMes(responseT.getData().toString());
                        for (FileBean fileBean : mFileList){
                            File f = new File(fileBean.getValue());
                            if (f.exists()){
                                f.delete();
                            }
                        }
                        BaseApp.setHistoryText(mUser.getUserId(),info.getCheckPoint());
                        mActivity.finish();
                    }

                    @Override
                    public void onError(int code, String msg, String errMsg) {
                        mView.hidePb_mes();
                        mView.showMes(msg);
                    }

                    @Override
                    public void onNext(ResponseT responseT) {
                        mView.hidePb_mes();
                    }
                });

        mCompositeDisposable.add(enqueue);
    }


    public void vaildPhone(String phone){
        mView.showPb();
        Disposable enqueue = RealNetWorkUtil.get().method("api-sms/communityPeople/checkPhone")
                .addParams("phone",phone)
                .build().enqueue(RegPeopleBean.class, new CallBackImpl<RegPeopleBean>() {
                    @Override
                    public void onError(int code, String msg, String errMsg) {
                        mView.hidePb();
                        mView.showMes(msg);
                    }

                    @Override
                    public void onNext(final RegPeopleBean o) {
                        mView.hidePb();
                        if (o!=null) {
                            CommonDialog commonDialog = new CommonDialog(mActivity, "该人员信息已登记");
                            commonDialog.setOnPosClick(new CommonDialog.OnPosClick() {
                                @Override
                                public void onClick() {
                                    mView.returnInfo(o);
                                }
                            });
                            commonDialog.show();
                        }
                    }
                });
        mCompositeDisposable.add(enqueue);
    }
}
